package com.stn.zjx.givingtreasure.activity.userwallet;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.jungly.gridpasswordview.GridPasswordView;
import com.jungly.gridpasswordview.PasswordType;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.scan.TransferScanActivity;
import com.stn.zjx.givingtreasure.activity.set.ForgetPayPassActivity;
import com.stn.zjx.givingtreasure.activity.set.PayPasswordSetActivity;
import com.stn.zjx.givingtreasure.activity.set.UserPhoneBindActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.GetUserMoneyDomain;
import com.stn.zjx.givingtreasure.domain.QueryUserProfileDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.ScanResultEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.PayNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserMoneyIntegralImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.widget.VirtualKeyboardView;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class UserTransferActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.scan_bt)
    RelativeLayout scanBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.check_bt)
    TextView checkBt;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.user_sex)
    ImageView userSex;
    @BindView(R.id.uuId)
    TextView uuId;
    @BindView(R.id.go_profie)
    RelativeLayout goProfie;
    @BindView(R.id.account_ll)
    LinearLayout accountLl;
    @BindView(R.id.delete_bt)
    RelativeLayout deleteBt;
    @BindView(R.id.money_edit)
    EditText moneyEdit;
    @BindView(R.id.use_money)
    TextView useMoney;
    @BindView(R.id.go_transfer_bt)
    ButtonBgUi goTransferBt;
    private int toUserId = 0;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onScanEvent(ScanResultEvent event) {
        switch (event.flag) {
            case ScanResultEvent.USER_Transfer:
                try {
                    JSONObject result = new JSONObject(event.data);
                    String content = result.getString("stnId");
                    if (content == null) {
                        return;
                    }
                    phoneEdit.setText(content);
                    phoneEdit.setSelection(phoneEdit.getText().length());
                    initUser(phoneEdit.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast(getString(R.string.xml_error));
                }

                break;
        }
    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.transfer));
        scanBt.setVisibility(View.VISIBLE);

        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(moneyEdit.getText().toString().trim())) {
                    goTransferBt.setAlpha(0.4f);
                    goTransferBt.setClickable(false);
                    deleteBt.setVisibility(View.GONE);
                } else {
                    goTransferBt.setAlpha(1.0f);
                    goTransferBt.setClickable(true);
                    deleteBt.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        deleteBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moneyEdit.getText().clear();
            }
        });

        goTransferBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (toUserId == 0) {
                    showToast(getString(R.string.no_check_user_no_transfer));
                    return;
                }

                try {
                    if (TextUtils.isEmpty(moneyEdit.getText().toString())) {
                        showToast(getString(R.string.money_is_not_null));
                        return;
                    }
                    if (Double.parseDouble(moneyEdit.getText().toString()) < 0.01) {
                        showToast(getString(R.string.money_not_is_zero));
                        return;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(getString(R.string.money_not_is_num));
                    return;
                }

                isCheckJoinPassword();
            }
        });

        goTransferBt.setClickable(false);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.activity_user_transfer);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.check_bt, R.id.scan_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.scan_bt:
                Bundle bundle = new Bundle();
                bundle.putInt("flag", ScanResultEvent.USER_Transfer);
                RxActivityTool.skipActivity(this, TransferScanActivity.class, bundle);
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.check_bt:
                if (TextUtils.isEmpty(phoneEdit.getText().toString())) {
                    showToast(getString(R.string.please_input_transfer_phone));
                    return;
                }
                initUser(phoneEdit.getText().toString());
                break;
        }
    }

    public void initUser(String likeName) {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        if (onlineUser == null) {
            return;
        }
        UserNetImpl.query_user_profile_by_userid_userphone(likeName,
                onlineUser.getToken(),
                onlineUser.getToken() + "_query_user_profile_by_userid_userphone",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response.isSuccessful()&&!isFinishing()){
                        QueryUserProfileDomain domain = new Gson().fromJson(response.body(), QueryUserProfileDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    RequestOptions options = new RequestOptions();
                                    options.placeholder(R.mipmap.default_avatar);
                                    Glide.with(UserTransferActivity.this)
                                            .asBitmap()
                                            .load(domain.getData().getUserAvatar())
                                            .apply(options)
                                            .into(new SimpleTarget<Bitmap>() {
                                                @Override
                                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                    avatarCiv.setImageBitmap(resource);
                                                }

                                                @Override
                                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                                    super.onLoadFailed(errorDrawable);
                                                    avatarCiv.setImageResource(R.mipmap.default_avatar);
                                                }
                                            });
                                    userNickname.setText(domain.getData().getUserNickname());
                                    switch (domain.getData().getUserSex()) {
                                        case 0:
                                            userSex.setVisibility(View.GONE);
                                            break;
                                        case 1:
                                            userSex.setImageResource(R.mipmap.male);
                                            userSex.setVisibility(View.VISIBLE);
                                            break;

                                        case 2:
                                            userSex.setImageResource(R.mipmap.female);
                                            userSex.setVisibility(View.VISIBLE);
                                            break;
                                    }
                                    uuId.setText("UUID: " + domain.getData().getUserId());
                                    accountLl.setVisibility(View.VISIBLE);
                                    toUserId = domain.getData().getUserId();
                                    break;
                                default:
                                    showToast(getString(R.string.query_no_user));
                                    accountLl.setVisibility(View.GONE);
                                    toUserId = 0;
                                    break;
                            }
                        }
                    }
                }
        );
    }

    public void getMoney() {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        if (onlineUser == null) {
            return;
        }
        UserMoneyIntegralImpl.get_money(onlineUser.getToken(), onlineUser.getToken() + "_get_money", new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.isSuccessful() && !isFinishing()) {
                    initMoney(response.body());
                }
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if (response.isSuccessful() && !isFinishing()) {
                    initMoney(response.body());
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    public void initMoney(String body) {
        GetUserMoneyDomain domain = new Gson().fromJson(body, GetUserMoneyDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                try {
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    useMoney.setText(getString(R.string.use_money) + " " + decimalFormat.format(domain.getData().getUserMoney()) + "" + getString(R.string.rmb));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getMoney();
    }

    public void transfer(String token,
                         String userPrivatepwd,
                         Integer toUserId,
                         String userMoney, Dialog dialog) {
        dialog.dismiss();
        PayNetImpl
                .user_transfer(token,
                        userPrivatepwd,
                        toUserId,
                        userMoney,
                        token + "_user_transfer",
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                switch (domain.getStatus()) {
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        finish();
//                                        moneyEdit.getText().clear();
//                                        getMoney();
//                                        showToast(domain.getMessage());
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                            }
                        });
    }

    public void isCheckJoinPassword() {
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
            return;
        }
        PayNetImpl
                .join_set_user_paypassword(UserService.getInstance(this).getOnlineLoginUser().getToken(),
                        "join_set_user_paypassword", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if(response.isSuccessful()&&!isFinishing()){
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            RxActivityTool.skipActivity(getApplicationContext(), PayPasswordSetActivity.class);
                                            break;
                                        case BaseApi.REQUEST_ChECK_PAY_PASSWORD_CODE:
                                            initPayDialog();
                                            break;
                                        default:
                                            showToast(domain.getMessage());
                                            break;
                                    }
                                }


                            }
                        });

    }


    public void initPayDialog() {
        Dialog pay_dialog;
        GridPasswordView gridPasswordView;
        VirtualKeyboardView virtualKeyboardView;
        GridView gridView;
        LinearLayout under;
        pay_dialog = new Dialog(this, R.style.dialog_soft_input);
        pay_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        pay_dialog.setContentView(R.layout.dialog_input_pay_password);
        WindowManager.LayoutParams lp = pay_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        pay_dialog.getWindow().setWindowAnimations(R.style.myDialogStyle);
        pay_dialog.getWindow().setAttributes(lp);
        View close = pay_dialog.findViewById(R.id.close);
        TextView forgetpassword_bt = pay_dialog.findViewById(R.id.forgetpassword_bt);
        gridPasswordView = pay_dialog.findViewById(R.id.grid_password_edit);
       gridPasswordView.mInputView.setFocusable(false);
        gridPasswordView.mInputView.setFocusableInTouchMode(false);
        virtualKeyboardView = pay_dialog.findViewById(R.id.virtualKeyboardView);
         gridView=pay_dialog.findViewById(R.id.gv_keybord);
        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        pay_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
//                // 获取焦点
//                gridPasswordView.requestFocus();
//                SoftInputUtils.openSoftInput(UserTransferActivity.this, pay_dialog.getCurrentFocus());
            }
        });
        pay_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                gridPasswordView.clearPassword();
//                gridPasswordView.requestFocus();
//                SoftInputUtils.closedSoftInput(UserTransferActivity.this);
            }
        });


        forgetpassword_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = UserService.getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (user == null) {
                    return;
                }
                if (TextUtils.isEmpty(user.getUserPhone())) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserPhoneBindActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", user.getUserPhone());
                    RxActivityTool.skipActivity(getApplicationContext(), ForgetPayPassActivity.class, bundle);
                }

            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                pay_dialog.dismiss();
            }
        });


        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (position < 11 && position != 9) {    //点击0~9按钮
                    if(gridPasswordView.getPassWord().length()<6){
                        gridPasswordView.setPassword(gridPasswordView.getPassWord()+virtualKeyboardView.getValueList().get(position).get("name"));
                    }
                    if(gridPasswordView.getPassWord().length()==6){
                        User onlineUser = UserService.getInstance(UserTransferActivity.this).getOnlineLoginUser();
                        if (onlineUser == null) {
                            return;
                        }
                        transfer(onlineUser.getToken(), gridPasswordView.getPassWord(), toUserId, moneyEdit.getText().toString().trim(), pay_dialog);
                    }
                } else {
                    if (position == 11) {      //点击退格键
                        if(gridPasswordView.getPassWord().length()>0){
                            gridPasswordView.setPassword(gridPasswordView.getPassWord().substring(0,gridPasswordView.getPassWord().length()-1));
                        }
                    }
                }
            }
        });

        pay_dialog.show();
    }
}
